/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: Shentong
 * @LastEditTime: 2021-11-19 15:52:49
 */
/**
 * @description 此页面暂时不用： TODO:
 */
import React, { useEffect, useState, useCallback, useMemo } from "react";
import Taro, { useRouter } from '@tarojs/taro'

 import { View, Text } from "@tarojs/components";

 import { orderStauts } from '@/src/constants/data'

 import { showToast } from '@/utils/index'

 import { getOrderDetail, reminder, refund } from '@/api/order'

import QrcodeCurtain from "@/src/components/custom/qrcodeCurtain";

 import { AtIcon, AtAvatar, AtTextarea, AtFloatLayout } from 'taro-ui'

 import styles from './index.module.scss'

 const OrderDetail = () => {
   const [orderInfo, setOrderInfo] = useState({});
   const [isOpened, setIsOpened] = useState<boolean>(false);

    // 查看二维码
  const [showQrModel, setShowQrModel] = useState<boolean>(false)
  const [qrcodeImg, setQrCodeImg] = useState<string>('')

   const [reason, setReason] = useState<string>('')


   const routerParams = useRouter().params;


   const callPhone = phoneNumber => {
    Taro.makePhoneCall({ phoneNumber })
  }

  const showRefundBtn = useMemo(()=> {
    return [1,2,3,4].includes(orderInfo.orderStatus)
  }, [orderInfo.orderStatus])

  // 再来一单
  const onceAgain = () => {
    Taro.navigateTo({
      url: `/pages/detail/index?shopId=${orderInfo.shopSId}`
    })
  }
  // 催单
  const reminderHandle = () => {
    reminder({ orderId: orderInfo.orderSId }).then(()=> {
      showToast('已催单~', {
        complete: () => initPage()
      })
    })
  }

  // 申请退款
  const reqRefundHandle = () => {
    setIsOpened(true)
  }

  const textAreaChange = (val) => setReason(val)

  // 模态框关闭事件
  const modalOnClose = () => {
     setIsOpened(false)
     setReason('')
  }

   // 提交退款申请
   const submitHandle = () => {
    if (!reason) return showToast("请输入退款原因")

    refund({ orderId: orderInfo.orderSId, reason }).then(() => {
      showToast("申请成功", {
        complete: () => {
          initPage()
          modalOnClose()
        }
      })
    })
  }


  const initPage = useCallback(() => {
    Taro.showLoading({ title: "加载中...", mask: true });

    getOrderDetail(routerParams).then((res:any = {}) => {
      setOrderInfo(res.data)

      Taro.hideLoading();
    })
  }, [routerParams])

  const getQrcode = (e, { code = '' }) => {
    e.stopPropagation()

    if (code ){
      var imgData = code.replace(/[\r\n]/g, '') // 将回车换行换为空字符''
      setShowQrModel(true)
      setQrCodeImg(imgData)
    }
  }

  useEffect(() => {
    initPage()
  }, [initPage]);

   return (
     <View className={styles.orderDetail}>
       <View className={styles.top}>
         <View className={styles.status}>订单{orderStauts[orderInfo.orderStatus]}</View>
         {
           orderInfo.eatCode ? (
             <View className={styles.orderSeq}>取餐码：<Text className={styles.txt}>{orderInfo.eatCode}</Text></View>
           ) : null
         }
       </View>
       {
        orderInfo.eatAddress ? (
          <View className={styles.eatAddressInfo}>
            <View className={styles.eatAddress}>
              取餐地址：<Text className={styles.txt}>{orderInfo.eatAddress}</Text>
            </View>
            <View className={styles.eatQrCode} onClick={(e) => getQrcode(e, orderInfo)}>查看二维码</View>
          </View>
        ) : null
       }
       <View className={styles.header}>
         <View className={styles.welcome}>感谢您的惠顾，欢迎下次光临</View>
         <View className={styles.btnGroup}>
          <View className={styles.aBtn} onClick={() => onceAgain()}>再来一单</View>
          { orderInfo.orderStatus === 1 ? <View className={styles.aBtn} onClick={()=> reminderHandle()}>催单</View> : null}
          { showRefundBtn ? <View className={styles.aBtn} onClick={()=> reqRefundHandle()}>申请退款</View> : null}
         </View>
       </View>
       <View className={styles.prodInfo}>
         <View className={styles.titlePhone}>
           <View className={styles.title}>{orderInfo.shopName}</View>
           <AtIcon value='phone' size='25' color='#F00' onClick={() => callPhone(`${orderInfo.shopPhone}`)}></AtIcon>
         </View>
         {
           orderInfo.goods?.map((item, index)=> {
            return (
              <View className={styles.ctx} key={`item_${index}`}>
                <AtAvatar image={item.goodsImageUrl} className={styles.headerImg} size='small'></AtAvatar>
                <View className={styles.rt}>
                  <View className={styles.content}>
                    <View className={styles.name}>{item.goodsName}</View>
                    <View className={styles.price}>￥{item.goodsPrice}</View>
                  </View>
                  <View className={styles.count}>x{item.goodsNum}</View>
                </View>
            </View>
            )
           })
         }
         <View className={styles.expressInfo}>
           <View className={styles.desc}>包装费</View>
            <View className={styles.price}>￥{orderInfo.goodsPackTotalPrice}</View>
         </View>
         <View className={styles.allAcount}>
           <View className={styles.cheap}>优惠￥{orderInfo.preferentialPrice}</View>
           <View className={styles.acount}>合计￥{orderInfo.actualPayment}</View>
         </View>
       </View>
       {/* 订单信息 */}
       <View className={styles.orderInfo}>
         <View className={styles.title}>订单信息</View>
         <View className={styles.item}>
           <View className={styles.label}>订单序号</View>
           <View className={styles.num} style={{fontWeight: 500,color: 'red'}}>{orderInfo.orderSeq}</View>
         </View>
         <View className={styles.item}>
           <View className={styles.label}>订单号码</View>
           <View className={styles.num}>{orderInfo.orderSNum}</View>
         </View>
         <View className={styles.item}>
           <View className={styles.label}>下单时间</View>
           <View className={styles.num}>{orderInfo.createTime}</View>
         </View>
         <View className={styles.item}>
           <View className={styles.label}>支付方式</View>
           <View className={styles.num}>{orderInfo.payType === 0 ? '微信': '支付宝'}</View>
         </View>
       </View>
       <View className={styles.shopInfo}>
         <View className={styles.item}>
           <View className={styles.label}>预计送达</View>
           <View className={styles.num}>{orderInfo.deliveryTime}</View>
         </View>
         <View className={styles.item}>
           <View className={styles.label}>用户电话</View>
           <View className={styles.num}>{orderInfo.receiverPhone}</View>
         </View>
         <View className={styles.item}>
           <View className={styles.label}>送达地址</View>
           <View className={styles.address}>{orderInfo.address}</View>
         </View>
       </View>
       <View className={styles.deliveryInfo}>
         <View className={styles.item}>
           <View className={styles.label}>配送员姓名</View>
           <View className={styles.num}>{orderInfo.deliveryName || '暂无信息'}</View>
         </View>
         <View className={styles.item}>
           <View className={styles.label}>配送员手机号</View>
           <View className={styles.num}>{orderInfo.deliveryPhone || '暂无信息'}</View>
         </View>
         <View className={`${styles.remark}`}>
           <View className={styles.label}>备注</View>
           <View className={`${styles.info} ${ !orderInfo.remark ? styles.noneInfo : '' }`}>{orderInfo.remark || '暂无信息'}</View>
         </View>
       </View>

       {/* 查看二维码弹出框 */}
      <QrcodeCurtain showModel={showQrModel} image={qrcodeImg} onCloseHandle={() =>setShowQrModel(false)} />

       {/* 申请退款模态框 */}
       <AtFloatLayout isOpened={isOpened} title='申请退款' onClose={modalOnClose}>
         <View className={styles.ressonBox}>
            <View className={styles.textAreaBox} catchMove>
              <AtTextarea
                value={reason}
                onChange={(val) => setReason(val)}
                height={170}
                maxLength={200}
                placeholder='请输入退款原因...'
                cursorSpacing={220}
                placeholderClass={styles.placeholderClass}
                showConfirmBar
              />
            </View>
            <View className={styles.operateBtn} onClick={submitHandle}>
              <View className={styles.txt}>提交</View>
            </View>
         </View>
       </AtFloatLayout>

     </View>
   );
 }

 export default OrderDetail
